//
//  SZLFuturesTableViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/7.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLFuturesTableViewController.h"
#import "FuturesTableViewCell.h"
#import "MyCountNetwork.h"
#import "SZLAccountHelper.h"
#import <MJRefresh.h>
#import "MBProgressHUD+MJ.h"
#import "UIAlertView+Entension.h"
#import "SZLSecondMarketViewController.h"

@interface SZLFuturesTableViewController ()<UITableViewDataSource,UITableViewDelegate,FuturesTableViewCellDelegate>

@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) NSMutableArray *sources;
@property (nonatomic,assign) NSInteger curPage;

@end

@implementation SZLFuturesTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的期货";
    self.curPage = 1;
    [self setTableView];
    [self getFuturesList];
}
- (void)setTableView
{
    if (!self.sourceTab.superview) {
        [self.view addSubview:self.sourceTab];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.sources.count-1) {
        return 210;
    }
    return 225;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sources.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FuturesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([FuturesTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.sources[indexPath.row];
    cell.delegate = self;
    return cell;
}
- (void)futuresTableViewCellClick:(FuturesActionType)type model:(MyFutureModel *)model
{
    __WEAK
    if (type == FuturesActionTypeRedeem) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入赎回理由" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alert show];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            if (btnIndex == 1) {
                UITextField *field = [alertView textFieldAtIndex:0];
                [self redeemAction:model reason:field.text];
            }
        }];
    }else if (type == FuturesActionTypePutMarket) {//放二级市场
        SZLSecondMarketViewController *secondVc = [[SZLSecondMarketViewController alloc]init];
        secondVc.model = model;
        secondVc.successBlock = ^(){
            [weakSelf getFuturesList];
        };
        [self.navigationController pushViewController:secondVc animated:YES];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"1.点击确认按钮，该期货到期后平台会联系到您将商品发货，同时将期货收益返现至您的虚拟账户中\n 2.如不选择或点击取消按钮，该期货到期后平台会将本金与收益一同返现至您的虚拟账户\n3.该选项一次生效，完成后不可进行修改" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert handlerClickedButton:^(UIAlertView *alertView, NSInteger btnIndex) {
            if (btnIndex == 1) {
                [weakSelf iWantWine:model];
            }
        }];
        [alert show];
    }
}
#pragma mark ------------期货列表------------------------------------
- (void)getFuturesList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showWaiter];
    [MyCountNetwork getMyFuturesListWithParame:parame response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        [self.sourceTab.mj_header endRefreshing];
        [self.sourceTab.mj_footer endRefreshing];
        if (success) {
            [self hideNoDataView];
            self.sourceTab.mj_footer.hidden = (lists.count<20);
            if (self.curPage == 1) {
                [self.sources removeAllObjects];
                (lists.count == 0)?[self showNoDataView:self.view.frame title:@"您还未购买期货"]:0;
            }else{
                (lists.count == 0)?[MBProgressHUD showError:@"没有更多数据了" toView:self.view]:0;
            }
            [self.sources addObjectsFromArray:lists];
            [self.sourceTab reloadData];
        }else{
            if ([msg isEqualToString:NoNetworkStatus]) {
                [self showRequestAgainView:@selector(getFuturesList)];
            }
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
- (void)redeemAction:(MyFutureModel *)model reason:(NSString *)reason
{
    
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"orderNo"] = model.orderNo;
    parame[@"reason"] = reason;
    [self showWaiter];
    [MyCountNetwork redeemQuickWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            model.status = 9;
            [self.sourceTab reloadData];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}

- (void)iWantWine:(MyFutureModel *)model
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"orderNo"] = model.orderNo;
    [self showWaiter];
    [MyCountNetwork wantWineWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"已成功提交" toView:self.view];
            [self getFuturesList];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}

- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-64) style:UITableViewStylePlain];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        _sourceTab.backgroundColor = RGBColorOne(240);
        _sourceTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([FuturesTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([FuturesTableViewCell class])];
        _sourceTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.curPage = 1;
            [self getFuturesList];
        }];
        _sourceTab.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.curPage++;
            [self getFuturesList];
        }];
    }
    return _sourceTab;
}

- (NSMutableArray *)sources
{
    if (!_sources) {
        _sources = [NSMutableArray array];
    }
    return _sources;
}

@end
